<template>
  <div class="online-edit-form" style="position: relative; height: 100%; min-height: 200px">
    <template v-if="dialogParams.fullscreen && !form2.openToTab && !dialogParams.isEdit">
      <el-container>
        <el-header style="height: 72px; background: white">
          <el-row
            type="flex"
            align="middle"
            style="justify-content: space-between; width: 100%; height: 100%"
          >
            <div style="display: flex; height: 40px; line-height: 40px">
              <!-- Jie. 20250719 有图标更好看一些 -->
              <i
                class="header-logo online-icon icon-orange-icon"
                style="font-size: 40px; color: #fda834; background: rgb(255 119 0 / 10%)"
              />
              <span style="font-size: 22px; color: #333; font-weight: bold">教育信息采集</span>
              <el-divider direction="vertical" style="height: 26px; margin: 7px 8px" />
              <span style="font-size: 18px; color: #333; font-weight: bold">{{
                form2.formName
              }}</span>
            </div>
            <el-button
              link
              size="default"
              :icon="Close"
              style="font-size: 24px; color: #909399"
              @click="onCancel"
            />
          </el-row>
        </el-header>
        <el-main style="width: 100%; padding: 15px; background: #f6f6f6">
          <el-row
            type="flex"
            justify="center"
            :style="{
              height:
                'calc(100vh - ' +
                (dialogParams.readOnly && (form2.operationList || []).length <= 0 ? 105 : 162) +
                'px)',
            }"
          >
            <div
              style="
                width: 8000px;
                max-width: 100vw;
                height: 100%;
                padding: 20px 15px;
                background: white;
              "
            >
              <el-scrollbar style="height: 100%" class="custom-scroll">
                <el-form
                  ref="formRef"
                  :model="formData"
                  class="full-width-input"
                  :rules="rules"
                  style="width: 100%"
                  :label-width="(form2.labelWidth || 100) + 'px'"
                  :label-position="form2.labelPosition || 'right'"
                  :size="layoutStore.defaultFormItemSize"
                  :validate-on-rule-change="false"
                  @submit.prevent
                >
                  <OnlineCustomBlock
                    v-if="isReady"
                    ref="root"
                    v-model:value="form2.widgetList"
                    height="100%"
                    :isEdit="dialogParams.isEdit"
                    :showBorder="false"
                    @widgetClick="onWidgetClick"
                  />
                </el-form>
              </el-scrollbar>
            </div>
          </el-row>
        </el-main>
        <!-- Jie. 20250719 修改底部按钮高度 -->
        <el-footer
          v-if="!dialogParams.readOnly || (form2.operationList || []).length > 0"
          style="background: white"
          height="60px;"
        >
          <el-row type="flex" justify="center" align="middle" style="height: 60px">
            <el-button
              v-for="operation in form2.operationList"
              :key="operation.id"
              size="default"
              style="margin-right: 16px"
              :type="operation.btnType"
              :plain="operation.plain"
              @click="onOperationClick(operation)"
            >
              {{ operation.name || SysCustomWidgetOperationType.getValue(operation.type) }}
            </el-button>
            <el-button
              v-if="!dialogParams.readOnly"
              type="primary"
              size="default"
              style="margin-right: 16px"
              @click="onSubmit"
            >
              保存
            </el-button>
            <el-button size="default" :plain="true" @click="onCancel"> 返回 </el-button>
          </el-row>
        </el-footer>
      </el-container>
    </template>
    <!-- Jie. 20250716 新增页签打开方式 -->
    <template v-else-if="form2.openToTab && !dialogParams.isEdit">
      <div class="tab-form-container">
        <!-- 操作按钮位置：顶部 -->
        <div
          v-if="form2.operationPos === 'top'"
          class="operation-bar"
          :style="{ textAlign: form2.operationAlign || 'left' }"
        >
          <el-button
            v-for="operation in form2.operationList"
            :key="operation.id"
            :size="layoutStore.defaultFormItemSize"
            :type="operation.btnType"
            :plain="operation.plain"
            @click="onOperationClick(operation)"
          >
            {{ operation.name || SysCustomWidgetOperationType.getValue(operation.type) }}
          </el-button>
          <el-button
            v-if="!dialogParams.readOnly"
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click="onSubmit"
          >
            保存
          </el-button>
          <!-- <el-button
            v-if="!dialogParams.readOnly"
            :size="layoutStore.defaultFormItemSize"
            :plain="true"
            @click="onCancel"
          >
            取消
          </el-button> -->
        </div>

        <!-- 表单内容 -->
        <div
          class="tab-form-content"
          :style="{ width: dialogParams.isEdit ? form2.pageWith || '100%' : '100%' }"
        >
          <el-scrollbar style="height: 100%" class="custom-scroll">
            <component
              :is="mode === 'pc' ? ElForm : VanForm"
              ref="formRef"
              :model="formData"
              class="full-width-input"
              :rules="rules"
              style="width: 100%"
              :label-width="(form2.labelWidth || 100) + 'px'"
              :label-position="form2.labelPosition || 'right'"
              :size="layoutStore.defaultFormItemSize"
              @submit.prevent
            >
              <OnlineCustomBlock
                v-if="isReady"
                ref="root"
                v-model:value="form2.widgetList"
                :height="height"
                :isEdit="dialogParams.isEdit"
                :showBorder="false"
                @widgetClick="onWidgetClick"
              />
            </component>
          </el-scrollbar>
        </div>

        <!-- 操作按钮位置：底部 -->
        <div
          v-if="form2.operationPos === 'bottom'"
          class="operation-bar"
          :style="{ textAlign: form2.operationAlign || 'left' }"
        >
          <el-button
            v-for="operation in form2.operationList"
            :key="operation.id"
            :size="layoutStore.defaultFormItemSize"
            :type="operation.btnType"
            :plain="operation.plain"
            @click="onOperationClick(operation)"
          >
            {{ operation.name || SysCustomWidgetOperationType.getValue(operation.type) }}
          </el-button>
          <!-- <el-button
            v-if="!dialogParams.readOnly"
            :size="layoutStore.defaultFormItemSize"
            :plain="true"
            @click="onCancel"
          >
            取消
          </el-button> -->
          <el-button
            v-if="!dialogParams.readOnly"
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click="onSubmit"
          >
            保存
          </el-button>
        </div>
      </div>
      <label class="page-close-box" @click="onClosePage()">
        <img src="@/assets/img/back2.png" alt="" />
      </label>
    </template>
    <template v-else>
      <div class="form-box" :style="{ 'min-height': dialogParams.isEdit ? height : '0px' }">
        <el-scrollbar style="height: 100%" class="custom-scroll">
          <component
            :is="mode === 'pc' ? ElForm : VanForm"
            ref="formRef"
            :model="formData"
            class="full-width-input"
            :rules="rules"
            style="width: 100%"
            :label-width="(form2.labelWidth || 100) + 'px'"
            :label-position="form2.labelPosition || 'right'"
            :size="layoutStore.defaultFormItemSize"
            @submit.prevent
          >
            <OnlineCustomBlock
              v-if="isReady"
              ref="root"
              v-model:value="form2.widgetList"
              :height="height"
              :isEdit="dialogParams.isEdit"
              :showBorder="false"
              @widgetClick="onWidgetClick"
            />
          </component>
        </el-scrollbar>
      </div>
      <el-row v-if="!dialogParams.isEdit" class="menu-box" type="flex" justify="end">
        <el-button
          v-for="operation in form2.operationList"
          :key="operation.id"
          :size="layoutStore.defaultFormItemSize"
          :type="operation.btnType"
          :plain="operation.plain"
          @click="onOperationClick(operation)"
        >
          {{ operation.name || SysCustomWidgetOperationType.getValue(operation.type) }}
        </el-button>
        <el-button
          v-if="!dialogParams.readOnly"
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :plain="true"
          @click="onCancel"
        >
          取消
        </el-button>
        <el-button
          v-if="!dialogParams.readOnly"
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onSubmit"
        >
          保存
        </el-button>
      </el-row>
    </template>
  </div>
</template>

<script setup lang="ts">
import { API_CONTEXT } from '@/api/config';
import { post } from '@/common/http/request';
// Jie. 20250822 导入Api脚本
import { OnlineApiController } from '@/api/online';
import { TableData } from '@/common/http/types';
import { OnlineFormEventType, SysCustomWidgetOperationType } from '@/common/staticDict';
import {
  SysOnlineColumnFilterType,
  SysOnlineFieldKind,
  SysOnlineRelationType,
} from '@/common/staticDict/online';
import { DialogProp } from '@/components/Dialog/types';
import { useThirdParty } from '@/components/thirdParty/hooks';
import { ThirdProps } from '@/components/thirdParty/types';
import OnlineCustomBlock from '@/online/components/OnlineCustomBlock.vue';
import widgetData from '@/online/config/index';
import { useLayoutStore, useLoginStore } from '@/store';
import { ANY_OBJECT } from '@/types/generic';
import { Close } from '@element-plus/icons-vue';
import { ElForm, ElMessage } from 'element-plus';
import { Form as VanForm } from 'vant';
import { useRouter, useRoute } from 'vue-router';
import { useDict } from '../../hooks/useDict';
import { useForm } from '../hooks/useForm';

const router = useRouter();
// Jie. 20250716 关闭页签
const route = useRoute();
const loginStore = useLoginStore();

interface IProps extends ThirdProps {
  formConfig: ANY_OBJECT;
  height?: string;
  // 主表数据
  masterTableData?: ANY_OBJECT;
  // 是否表单编辑模式
  isEdit?: boolean;
  // 是否复制
  isCopy?: boolean;
  // 是否更新
  isUpdate?: boolean;
  // 更新数据的主键
  updateIdList?: string[];
  readOnly?: boolean;
  // 当前选中组件
  currentWidget?: ANY_OBJECT | null;
  // 需要编辑数据，如果是null则是新增
  rowData?: ANY_OBJECT;
  // 是否全屏弹窗
  fullscreen?: boolean;
  // 是否保存到数据库
  saveData?: boolean;
  mode?: string;
  // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
  dialog?: DialogProp<ANY_OBJECT>;
  // 流程定义key
  processDefinitionKey?: string;
  // 任务变量
  taskVariableList?: ANY_OBJECT[];
}

const emit = defineEmits<{
  widgetClick: [ANY_OBJECT | null];
}>();

const props = withDefaults(defineProps<IProps>(), {
  isEdit: false,
  isUpdate: false,
  updateIdList: undefined,
  readOnly: false,
  fullscreen: false,
  saveData: true,
  mode: 'pc',
});

const layoutStore = useLayoutStore();
const { onCloseThirdDialog } = useThirdParty(props);

const formRef = ref();
const { getDictDataList } = useDict();

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  } else {
    onCloseThirdDialog(false);
  }
};

// Jie. 20250716 关闭页签
const onClosePage = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
};

const {
  isReady,
  rules,
  dialogParams,
  form: form2,
  formData,
  masterTable,
  isRelation,
  tableWidgetList,
  richEditWidgetList,
  getWidgetValue,
  getWidgetVisible,
  onValueChange,
  onWidgetValueChange,
  getPrimaryData,
  getDropdownParams,
  checkOperationPermCode,
  checkOperationDisabled,
  checkOperationVisible,
  cloneWidget,
  handlerOperation,
  handlerScriptOperation,
  // Jie. 20250422 表格实例
  tableInstance,
  showSelectDialog,
  loadOnlineFormConfig,
  getTableData,
  setTableData,
  initPage,
  initFormWidgetList,
  initWidgetRule,
  getIgnoreMaskFields,
  initWidgetLinkage,
  onPrint,
  showDialog,
  showOnlineDialog,
  onStartFlowImpl,
  masterTablePrimaryKey,
  instanceData,
} = useForm({
  props,
  router,
  formRef,
  close: onCancel,
});
provide('form', () => {
  return {
    ...form2.value,
    mode: props.mode || 'pc',
    isEdit: dialogParams.value.isEdit,
    readOnly: dialogParams.value.readOnly,
    formData: formData,
    getWidgetValue: getWidgetValue,
    getWidgetVisible: getWidgetVisible,
    onValueChange: onValueChange,
    onWidgetValueChange: onWidgetValueChange,
    getTableData: getTableData,
    setTableData: setTableData,
    getPrimaryData: getPrimaryData,
    getDropdownParams: getDropdownParams,
    checkOperationPermCode: checkOperationPermCode,
    checkOperationDisabled: checkOperationDisabled,
    checkOperationVisible: checkOperationVisible,
    cloneWidget: cloneWidget,
    handlerOperation: handlerOperation,
    handlerScriptOperation: handlerScriptOperation,
    tableInstance: tableInstance,
    showSelectDialog: showSelectDialog,
    getDictDataList: getDictDataList,
    loadOnlineFormConfig: loadOnlineFormConfig,
    isActive: (widget: ANY_OBJECT) => {
      return props.currentWidget === widget;
    },
    getWidgetObject: widgetData.getWidgetObject,
    instanceData: () => instanceData,
  };
});

const onInput = (widgetList: ANY_OBJECT[]) => {
  form2.value.widgetList = widgetList;
};

const onWidgetClick = (widget: ANY_OBJECT | null) => {
  emit('widgetClick', widget);
};
const onOperationClick = (operation: ANY_OBJECT) => {
  if (operation.type === SysCustomWidgetOperationType.PRINT) {
    let keyName;
    if (masterTable.value.relation == null) {
      keyName = masterTable.value.datasource.variableName;
    } else {
      keyName = masterTable.value.relation.variableName;
    }
    onPrint(operation, formData[keyName], null, form2.value.formName);
  } else if (operation.type === SysCustomWidgetOperationType.SCRIPT) {
    handlerScriptOperation(operation);
  } else {
    let updateIdList = [];
    handlerOperation(operation, {
      isEdit: dialogParams.value.isEdit,
      isUpdate: operation.type === SysCustomWidgetOperationType.UPDATE_DIALOG,
      updateIdList: updateIdList,
      masterTableData: dialogParams.value.masterTableData,
    });
  }
};

// 提交表单数据
const onSaveFormData = async () => {
  if (masterTable.value == null || masterTable.value.datasource == null) {
    ElMessage.error('表单使用主数据源或主表不存在！');
    throw new Error();
  }
  let params: ANY_OBJECT = {
    datasourceId: masterTable.value.datasource.datasourceId,
    relationId: (masterTable.value.relation || {}).relationId,
    masterData: isRelation.value ? undefined : formData[masterTable.value.datasource.variableName],
  };

  console.log('后续需求增加更改地方~~~~~~~~~~~~~~');

  if (isRelation.value) {
    // 从表数据添加或更新
    params.slaveData = {
      ...formData[masterTable.value.relation.variableName],
    };
    // 设置关联字段的值
    let slaveColumnValue = (dialogParams.value.masterTableData || {})[
      masterTable.value.relation.masterColumn.columnName
    ];
    if (slaveColumnValue != null) {
      params.slaveData[masterTable.value.relation.slaveColumn.columnName] = slaveColumnValue;
    }
  } else {
    // 设置一对多从表数据
    params.slaveData = tableWidgetList.reduce((retObj, widget) => {
      if (widget.relation != null) {
        retObj[widget.relation.variableName] = formData[widget.relation.variableName];
      }
      return retObj;
    }, {});
  }

  // 执行提交数据前脚本
  if (
    !dialogParams.value.isEdit &&
    typeof form2.value.eventInfo[OnlineFormEventType.BEFORE_COMMIT_FORM_DATA] === 'function'
  ) {
    params = await form2.value.eventInfo[OnlineFormEventType.BEFORE_COMMIT_FORM_DATA](
      params,
      instanceData,
    );
    // Jie. 20250427 参数如果为空或者false不继续执行
    if (!params) {
      return;
    }
  }
  if (params == null) {
    throw new Error();
  }

  // 把slaveData里的relationVariableName替换成relationId
  if (!isRelation.value && params.slaveData) {
    let slaveDataKeyList = Object.keys(params.slaveData);
    if (slaveDataKeyList.length > 0) {
      let relationVariableNameMap = new Map();
      form2.value.tableMap.forEach((table: ANY_OBJECT) => {
        if (table.relation != null) {
          relationVariableNameMap.set(table.relation.variableName, table.relation.relationId);
        }
      });
      slaveDataKeyList.forEach(key => {
        let relationId = relationVariableNameMap.get(key);
        if (relationId != null) {
          params.slaveData[relationId] = params.slaveData[key];
        }
        params.slaveData[key] = undefined;
      });
    }
  }

  let needStartFlow = false;

  if (
    !isRelation.value &&
    props.processDefinitionKey != null &&
    props.processDefinitionKey !== ''
  ) {
    needStartFlow = true;
  }
  // Jie. 20250822 检查是否使用自定义保存API
  let res;
  if (form2.value.customSaveApi) {
    const { saveApiType, saveApiUrl, saveApiScript } = form2.value;
    if (saveApiType === 'api' && !saveApiUrl) {
      throw new Error('请设置表单自定义保存ApiUrl');
    }
    if (saveApiType === 'script' && !saveApiScript) {
      throw new Error('请设置表单自定义保存Api脚本');
    }

    // Jie. 20250822 清理数据结构，去除DictMap等字段，转换从表ID为变量名
    const cleanedParams = cleanDataForCustomApi(params);

    if (saveApiType === 'api') {
      res = await post(saveApiUrl, cleanedParams);
    } else if (saveApiType === 'script') {
      res = await OnlineApiController.runScript({
        scriptCode: saveApiScript,
        scriptParam: cleanedParams,
      });
    }
  } else {
    // 默认保存逻辑
    let commitUrl;
    if (isRelation.value) {
      // 从表提交数据
      commitUrl =
        dialogParams.value.rowData == null || dialogParams.value.isCopy
          ? API_CONTEXT + '/online/onlineOperation/addOneToManyRelation/'
          : API_CONTEXT + '/online/onlineOperation/updateOneToManyRelation/';
    } else {
      // 主表提交数据
      commitUrl =
        dialogParams.value.rowData == null || dialogParams.value.isCopy
          ? API_CONTEXT + '/online/onlineOperation/addDatasource/'
          : API_CONTEXT + '/online/onlineOperation/updateDatasource/';
    }
    commitUrl += masterTable.value.datasource.variableName;
    res = await post(commitUrl, params);
  }
  if (!needStartFlow) {
    ElMessage.success('保存成功！');
    if (props.dialog) {
      props.dialog.submit(res, formData);
    } else {
      onCloseThirdDialog(true, dialogParams.value.rowData, res);
    }
  } else if (res.data) {
    formData[masterTable.value.datasource.variableName][masterTablePrimaryKey.value] = res.data;
  }
  if (needStartFlow) {
    try {
      await onStartFlowImpl(
        props.processDefinitionKey,
        props.taskVariableList,
        formData[masterTable.value.datasource.variableName],
      );
      ElMessage.success('保存并启动成功！');
      if (props.dialog) {
        props.dialog.submit(res, formData);
      } else {
        onCloseThirdDialog(true, dialogParams.value.rowData, res);
      }
    } catch (e) {
      if (props.dialog) {
        props.dialog.submit(res, formData);
      } else {
        onCloseThirdDialog(true, dialogParams.value.rowData, res);
      }
    }
  }
};

// 更新数据
const onUpdateFormData = () => {
  let params = {
    datasourceId: masterTable.value.datasource.datasourceId,
    relationId: (masterTable.value.relation || {}).relationId,
    masterData: isRelation.value ? undefined : formData[masterTable.value.datasource.variableName],
    slaveData: isRelation.value
      ? {
          ...formData[masterTable.value.relation.variableName],
        }
      : undefined,
    dataIdList: dialogParams.value.updateIdList,
  };
  let httpCall;
  if (params.relationId) {
    httpCall = post(
      API_CONTEXT +
        '/online/onlineOperation/updateOneToManyRelationBatch/' +
        masterTable.value.datasource.variableName,
      params,
    );
  } else {
    httpCall = post(
      API_CONTEXT +
        '/online/onlineOperation/updateDatasourceBatch/' +
        masterTable.value.datasource.variableName,
      params,
    );
  }
  httpCall
    .then(res => {
      ElMessage.success('保存成功！');
      if (props.dialog) {
        props.dialog.submit(res);
      } else {
        onCloseThirdDialog(true, dialogParams.value.rowData, res);
      }
    })
    .catch(e => {
      console.warn(e);
    });
};

const tempArr = ref([])

// 提交
const onSubmit = () => {
  if (dialogParams.value.isEdit) return;
  if (Array.isArray(richEditWidgetList)) {
    richEditWidgetList.forEach(richWidget => {
      if (richWidget && richWidget.widgetImpl) {
        onValueChange(richWidget, richWidget.widgetImpl.getHtml());
      }
    });
  }
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    // 更新字段
    if (dialogParams.value.isUpdate) {
      onUpdateFormData();
      return;
    }
    if (dialogParams.value.saveData) {
      // 非级联保存数据
      onSaveFormData().catch(e => {
        console.error(e);
      });
    } else {
      // 级联添加返回表单数据到父表单
      let data = formData;

      if (
        !dialogParams.value.isEdit &&
        typeof form2.value.eventInfo[OnlineFormEventType.BEFORE_COMMIT_FORM_DATA] === 'function'
      ) {
        data = await form2.value.eventInfo[OnlineFormEventType.BEFORE_COMMIT_FORM_DATA](
          formData,
          instanceData,
        );
      }


      if (props.dialog) {
        props.dialog.submit(data);
      } else {
        onCloseThirdDialog(true, dialogParams.value.rowData, data);
      }
    }
  });
};

const clearFormData = (data: ANY_OBJECT | null, columnList: string[]) => {
  if (data == null) return;
  columnList.forEach(columnName => {
    data[columnName] = undefined;
  });
};

// Jie. 20250822 清理自定义API/脚本数据结构
const cleanDataForCustomApi = (params: ANY_OBJECT) => {
  const cleanedParams = JSON.parse(JSON.stringify(params));
  const fieldsToRemove = ['DictMap', 'DictMapList', '_X_ROW_KEY', '__cascade_add_id__'];
  const cleanObject = (obj: ANY_OBJECT) => {
    if (!obj || typeof obj !== 'object') return obj;

    Object.keys(obj).forEach(key => {
      // 检查是否需要删除的字段
      const shouldRemove = fieldsToRemove.some(suffix => {
        if (suffix === '_X_ROW_KEY' || suffix === '__cascade_add_id__') {
          return key === suffix;
        }
        return key.endsWith(suffix);
      });

      if (shouldRemove) {
        delete obj[key];
      } else if (typeof obj[key] === 'object' && obj[key] !== null) {
        if (Array.isArray(obj[key])) {
          obj[key] = obj[key].map((item: ANY_OBJECT) => cleanObject(item));
        } else {
          cleanObject(obj[key]);
        }
      }
    });

    return obj;
  };

  // 清理主表数据
  if (cleanedParams.masterData) {
    cleanObject(cleanedParams.masterData);
  }

  // 清理从表数据，并将ID键转换为变量名
  if (cleanedParams.slaveData) {
    const newSlaveData: ANY_OBJECT = {};

    Object.keys(cleanedParams.slaveData).forEach(key => {
      // 查找对应的表信息，将relationId转换为variableName
      let variableName = key;

      // 从表单配置中查找对应的relation信息
      if (form2.value.tableMap) {
        form2.value.tableMap.forEach((table: ANY_OBJECT) => {
          if (table.relation && table.relation.relationId === key) {
            variableName = table.relation.variableName;
          }
        });
      }

      // 清理从表数据中的字段
      const cleanedSlaveData = cleanedParams.slaveData[key];
      if (Array.isArray(cleanedSlaveData)) {
        newSlaveData[variableName] = cleanedSlaveData.map((item: ANY_OBJECT) => cleanObject(item));
      } else {
        newSlaveData[variableName] = cleanObject(cleanedSlaveData);
      }
    });

    cleanedParams.slaveData = newSlaveData;
  } else {
    // 没有从表数据，但是需要给空对象，否则会报错
    cleanedParams.slaveData = {};
  }
  return cleanedParams;
};
const loadRelationTableData = async (widget: ANY_OBJECT) => {
  if (widget == null || widget.datasource == null || widget.relation == null) throw new Error();
  let params: ANY_OBJECT = {
    datasourceId: widget.datasource.datasourceId,
    relationId: widget.relation.relationId,
    filterDtoList: [
      {
        tableName: widget.table.tableName,
        columnName: widget.relation.slaveColumn.columnName,
        filterType: SysOnlineColumnFilterType.EQUAL_FILTER,
        columnValue: (formData[widget.datasource.variableName] || {})[
          widget.relation.masterColumn.columnName
        ],
      },
    ],
  };
  // 脱敏设置
  params.ignoreMaskFields = getIgnoreMaskFields(widget);
  if (!Array.isArray(params.orderParam) || params.orderParam.length <= 0) {
    // Jie. 20050418 增加排序参数
    let { orderColumn, orderAsc } = widget.props;
    if (orderColumn) {
      params.orderParam = [
        {
          fieldName: orderColumn,
          asc: !!orderAsc,
        },
      ];
    }
  }

  if (
    !dialogParams.value.isEdit &&
    typeof widget.eventInfo[OnlineFormEventType.BEFORE_LOAD_TABLE_DATA] === 'function'
  ) {
    params = await widget.eventInfo[OnlineFormEventType.BEFORE_LOAD_TABLE_DATA](
      params,
      instanceData,
    );
  }
  if (params == null) {
    throw new Error();
  }
  let res = await post<TableData<ANY_OBJECT>>(
    API_CONTEXT +
      '/online/onlineOperation/listByOneToManyRelationId/' +
      widget.datasource.variableName,
    params,
  );
  if (
    !dialogParams.value.isEdit &&
    typeof widget.eventInfo[OnlineFormEventType.AFTER_LOAD_TABLE_DATA] === 'function'
  ) {
    res.data.dataList = await widget.eventInfo[OnlineFormEventType.AFTER_LOAD_TABLE_DATA](
      res.data.dataList,
      instanceData,
    );
  }
  // 复制数据，清空主键id以及自动编码字段
  if (dialogParams.value.isCopy) {
    let temp = new Date().getTime();
    let autoCodeColumnName: string[] = [];
    if (widget.table && Array.isArray(widget.table.columnList)) {
      widget.table.columnList.forEach((column: ANY_OBJECT) => {
        if (column.fieldKind === SysOnlineFieldKind.AUTO_CODE) {
          autoCodeColumnName.push(column.columnName);
        }
      });
    }
    res.data.dataList.forEach(item => {
      if (widget.primaryColumnName) item[widget.primaryColumnName] = undefined;
      item.__cascade_add_id__ = temp++;
      autoCodeColumnName.forEach(columnName => {
        item[columnName] = undefined;
      });
    });
  }
  formData[widget.relation.variableName] = res.data.dataList;
};
const initFormData = () => {
  if (dialogParams.value.rowData != null) {
    return new Promise<void>((resolve, reject) => {
      // 如果是复制，清空主键以及自动编码字段
      let clearColumnList: string[] = [];
      if (dialogParams.value.isCopy && masterTable && Array.isArray(masterTable.value.columnList)) {
        masterTable.value.columnList.forEach((column: ANY_OBJECT) => {
          if (column.primaryKey || column.fieldKind === SysOnlineFieldKind.AUTO_CODE) {
            clearColumnList.push(column.columnName);
          }
        });
      }
      if (isRelation.value) {
        Object.keys(dialogParams.value.rowData).forEach(key => {
          formData[masterTable.value.relation.variableName][key] = dialogParams.value.rowData[key];
        });
        clearFormData(formData[masterTable.value.relation.variableName], clearColumnList);
        resolve();
      } else {
        // 初始化主表以及一对一字段数据
        let relationNameList: string[] = [];
        let datasourceName = '';
        form2.value.tableMap.forEach((table: ANY_OBJECT) => {
          if (table.relation && table.relation.relationType === SysOnlineRelationType.ONE_TO_ONE) {
            relationNameList.push(table.relation.variableName);
            table.columnList.forEach(column => {
              formData[table.relation.variableName][column.columnName] = undefined;
            });
          } else if (table.relation == null) {
            datasourceName = table.datasource.variableName;
          }
        });
        Object.keys(dialogParams.value.rowData).forEach(key => {
          if (relationNameList.indexOf(key) === -1) {
            // 主表字段
            formData[datasourceName][key] = dialogParams.value.rowData[key];
          } else {
            // 从表字段
            if (dialogParams.value.rowData[key]) {
              Object.keys(dialogParams.value.rowData[key]).forEach(subKey => {
                formData[key][subKey] = dialogParams.value.rowData[key][subKey];
                if (dialogParams.value.rowData[key][subKey + 'DictMapList']) {
                  formData[key][subKey + 'DictMapList'] =
                    dialogParams.value.rowData[key][subKey + 'DictMapList'];
                }
              });
            }
          }
        });
        // 初始化一对多数据
        if (Array.isArray(tableWidgetList) && tableWidgetList.length > 0) {
          try {
            let httpCallList = tableWidgetList
              .map(widget => {
                if (
                  widget.relation &&
                  widget.relation.relationType === SysOnlineRelationType.ONE_TO_MANY
                ) {
                  return loadRelationTableData(widget);
                }
                return null;
              })
              .filter(item => item != null);
            Promise.all(httpCallList)
              .then(() => {
                clearFormData(formData[datasourceName], clearColumnList);
                resolve();
              })
              .catch(e => {
                console.log(e);
                clearFormData(formData[datasourceName], clearColumnList);
                reject(e);
              });
          } catch (e) {
            console.log(e);
          }
        } else {
          clearFormData(formData[datasourceName], clearColumnList);
          resolve();
        }
      }
    });
  } else {
    return Promise.resolve();
  }
};

onMounted(() => {
  isReady.value = false;
  if (!dialogParams.value.isEdit) {
    if (
      form2.value.eventInfo &&
      typeof form2.value.eventInfo[OnlineFormEventType.AFTER_CREATE_FORM] === 'function'
    ) {
      form2.value.eventInfo[OnlineFormEventType.AFTER_CREATE_FORM](instanceData);
    }
    initWidgetRule();
    initFormData()
      .then(() => {
        if (
          form2.value.eventInfo &&
          typeof form2.value.eventInfo[OnlineFormEventType.AFTER_LOAD_FORM_DATA] === 'function'
        ) {
          form2.value.eventInfo[OnlineFormEventType.AFTER_LOAD_FORM_DATA](instanceData);
        }
        initWidgetLinkage();
        setTimeout(() => {
          formRef.value.clearValidate();
        });
        isReady.value = true;
      })
      .catch((e: Error) => {
        console.error(e);
        isReady.value = true;
      });
  } else {
    isReady.value = true;
  }
});
</script>

<style lang="scss" scoped>
.header-logo {
  display: inline-block;
  width: 40px;
  height: 40px;
  margin-right: 8px;
  text-align: center;
  color: #fda834;
  background: rgb(255 119 0 / 10%);
  border-radius: 8px;
  line-height: 40px;
}
.el-divider--vertical {
  height: 26px;
  margin: 7px 15px;
}
.online-edit-form {
  display: flex;
  flex-direction: column;
}
.online-edit-form .info {
  position: absolute;
  top: 30%;
  width: 100%;
  text-align: center;
  vertical-align: middle;
}
.form-box {
  flex-grow: 1;
  flex-shrink: 1;
  height: 300px;
}
.menu-box {
  flex-grow: 0;
  flex-shrink: 0;
}

// Jie. 20250618 新增页签打开方式
.tab-form-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 200px;

  .operation-bar {
    padding: 12px 16px;
    background: #ffffff;
    margin-bottom: 16px;
    gap: 16px;

    &:last-child {
      margin-top: 16px;
      margin-bottom: 0;
    }

    .el-button {
      &:last-child {
        margin-right: 0;
      }
    }
  }

  .tab-form-content {
    flex: 1;
    padding: 16px;
    overflow: auto;
    background: #ffffff;
  }
}
</style>
